package com.szholly.pro.watergas_server.ps.android.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.util.CollectionUtils;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.android.bean.QcTaskParam;
import com.szholly.pro.watergas_server.ps.android.common.DateTime;
import com.szholly.pro.watergas_server.ps.android.common.FieldInterceptor;
import com.szholly.pro.watergas_server.ps.android.common.NonNullUtil;
import com.szholly.pro.watergas_server.ps.android.common.SecurityConfig;
import com.szholly.pro.watergas_server.ps.android.common.SqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.TableRowMap;
import com.szholly.pro.watergas_server.ps.android.common.ValidUtils;
import com.szholly.pro.watergas_server.ps.android.controller.QcControl;
import com.szholly.pro.watergas_server.ps.android.controller.QcService;
import com.szholly.pro.watergas_server.ps.data.OperationTaskRow;
import com.szholly.pro.watergas_server.ps.data.OperationTaskTable;
import com.szholly.pro.watergas_server.ps.data.QcSampledataRow;
import com.szholly.pro.watergas_server.ps.data.QcSampledataTable;
import com.szholly.pro.watergas_server.ps.data.QcSampledetaildataRow;
import com.szholly.pro.watergas_server.ps.data.QcSampledetaildataTable;
import com.szholly.pro.watergas_server.ps.data.QcSamplenumberPersonRow;
import com.szholly.pro.watergas_server.ps.data.QcSamplenumberPersonTable;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONObject;

public class QcTaskSampleStrategy extends QcTaskStrategy {
	private QcService mDomainManager = QcService.get();
	private QcBatchService mBatchService = QcBatchService.INSTANCE;

	private String[] SAMPLE_DATA_ARRAY = { QcSampledataRow.FIELD_Company, QcSampledataRow.FIELD_Datatime, QcSampledataRow.FIELD_Ispxy, QcSampledataRow.FIELD_Monitortype, QcSampledataRow.FIELD_Qctype, QcSampledataRow.FIELD_Samplenumber, QcSampledataRow.FIELD_Samplephoto };

	public QcTaskSampleStrategy(QcOperationService mOperationService) {
		super(mOperationService);
	}

	@Override
	public List<RowBase> getTaskList(QcTaskParam taskParam) throws Exception {
		String companyCode = taskParam.getCompanyCode();
		String pointCode = taskParam.getPointCode();
		List<RowBase> taskList = getTaskList(companyCode, pointCode, null);

		List<RowBase> completeTaskList = completeTaskDataDes(taskList);
		List<RowBase> batchList = mBatchService.getSampleBatchList(companyCode);
		List<RowBase> resultList = new ArrayList<>();
		resultList.addAll(batchList);
		resultList.addAll(completeTaskList);
		return resultList;
	}

	@Override
	public RowBase addTask(QcTaskParam taskParam) throws Exception {
		String parentCode = taskParam.getParentTaskCode();
		// 编号为空表示增加的的是批次任务，不为空表示增加的是采样任务
		if (StringUtils.IsNullOrSpace(parentCode)) {
			String batchCode = taskParam.getTaskCode();
			String companyCode = taskParam.getCompanyCode();
			String userCode = taskParam.getUserId();
			return mBatchService.addBatch(batchCode, companyCode, "", userCode);
		} else {
			return addAndGetSampleOperationTask(taskParam);
		}
	}

	private RowBase addAndGetSampleOperationTask(QcTaskParam taskParam) throws Exception {
		String parentCode = taskParam.getParentTaskCode();
		String userId = taskParam.getUserId();
		String taskTypeCode = taskParam.getTaskTypeCode();
		String companyCode = taskParam.getCompanyCode();
		String pointCode = taskParam.getPointCode();
		String jobCode = QcControl.getTaskGuid(taskTypeCode);
		String taskCode = "qc" + new DateTime().toString("yyyyMMddHHmmss") + QcOperationService.createSuffix();
		ValidUtils.hasText(userId, "用户编号为空");
		ValidUtils.hasText(taskTypeCode, "任务类型编号为空");
		ValidUtils.hasText(jobCode, "任务编码编号为空");

		OperationTaskRow row = new OperationTaskRow();
		if (!StringUtils.IsNullOrSpace(companyCode)) {
			row.setWwtpId(companyCode);
		}
		if (!StringUtils.IsNullOrSpace(pointCode)) {
			row.setStationId(pointCode);
		}
		row.setStartTime(new Date());
		row.setFinishBy(userId);
		row.setJobId(jobCode);
		row.setTaskCode(taskCode);
		row.setTaskStatus("0");
		row.setParentTaskCode(parentCode);
		SqlUtils.insert(OperationTaskTable.TABLE_NAME, row);

		List<RowBase> taskList = getTaskList(companyCode, pointCode, taskCode);
		ValidUtils.notEmpty(taskList);
		return taskList.get(0);
	}

	@Override
	public void deleteTask(QcTaskParam taskParam) throws Exception {
		String taskCode = taskParam.getTaskCode();
		String parentTaskCode = taskParam.getParentTaskCode();
		if (StringUtils.IsNullOrSpace(parentTaskCode)) {
			mBatchService.delete(taskCode);
		} else {
			mOperationService.deleteOperationTask(taskParam);
		}
	}

	@Override
	public void deleteProcessedTask(QcTaskParam taskParam) throws Exception {
		String userId = taskParam.getUserId();
		String taskCode = taskParam.getTaskCode();

		SecurityConfig config = SecurityConfig.get(userId);
		ValidUtils.isTrue(config.containQcDeleteProcessedTask, "权限不够");
		try {
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			mOperationService.deleteOperationTask(taskParam);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public RowBase getProcessedTaskInitData(QcTaskParam taskParam) throws Exception {
		String taskCode = taskParam.getTaskCode();
		String companyCode = taskParam.getCompanyCode();
		String pointCode = taskParam.getPointCode();
		List<RowBase> parameterList = mParameterService.getSampleParameterList(pointCode);
		List<RowBase> labParameterList = mParameterService.getLabBasicParameterList(pointCode);
		List<RowBase> qcTypeList = mDomainManager.getSampleQcTypeList();
		List<RowBase> personList = mDomainManager.getPersonList(companyCode, "1");

		// 初始化样品编号
		List<RowBase> sampleDetailList = getSampleList(taskCode);
		validSampleList(sampleDetailList);
		RowBase sample1 = sampleDetailList.get(0);
		RowBase sample2 = null;
		if (sampleDetailList.size() == 2) {
			sample2 = sampleDetailList.get(1);
		}

		List<RowBase> valueDetailList = getValueList(taskCode);
		Map<String, Map<String, String>> valueMap1 = new HashMap<>();
		Map<String, Map<String, String>> valueMap2 = new HashMap<>();

		Set<String> allParameterSet = new HashSet<>();
		if (!CollectionUtils.isEmpty(valueDetailList)) {
			for (RowBase rowBase : valueDetailList) {
				Map<String, String> value = new HashMap<>();
				value.put("value", rowBase.getSafeString(QcSampledetaildataRow.FIELD_Monitorvalue));
				String isPxy = rowBase.getSafeString(QcSampledataRow.FIELD_Ispxy);
				String type = rowBase.getSafeString(QcSampledetaildataRow.FIELD_Type);
				String parameterCode = rowBase.getSafeString(QcSampledetaildataRow.FIELD_Monitorparam);

				if (!"1".equals(type)) {
					if ("1".equals(isPxy)) {// 平行样
						valueMap2.put(parameterCode, value);
					} else {// 普通样
						valueMap1.put(parameterCode, value);
					}
					allParameterSet.add(parameterCode);
				}
			}
		}

		List<RowBase> personDetailList = getPersonList(taskCode);
		List<String> selectPersonList1 = new ArrayList<>();
		List<String> selectPersonList2 = new ArrayList<>();
		if (!CollectionUtils.isEmpty(personDetailList)) {
			for (RowBase rowBase : personDetailList) {
				String personCode = rowBase.getSafeString(QcSamplenumberPersonRow.FIELD_Samplepersoncode);
				String isPxy = rowBase.getSafeString(QcSampledataRow.FIELD_Ispxy);
				if ("1".equals(isPxy)) {
					selectPersonList2.add(personCode);
				} else {
					selectPersonList1.add(personCode);
				}
			}
		}

		// 初始化质控类型
		String qcTypeCode = sample1.getSafeString(QcSampledataRow.FIELD_Qctype);
		for (RowBase rowBase : qcTypeList) {
			if (qcTypeCode.equals(rowBase.get("id"))) {
				rowBase.put("checked", true);
				break;
			}
		}

		// 初始化实验参数类型
		Map<String, Set<String>> labParameterMap = getLabParameterMap(taskCode);
		Set<String> selectParameterList1 = labParameterMap.get("0");
		Set<String> selectParameterList2 = labParameterMap.get("1");

		// 初始化时间
		String dateTime = sample1.getSafeString(QcSampledataRow.FIELD_Createtime);

		// 初始化样品编号
		String sampleCode1 = sample1.getSafeString(QcSampledataRow.FIELD_Samplenumber);
		String sampleCode2 = null;
		if (sample2 == null) {
			String rule = QcService.getSamplePrefix(companyCode);// 命名规则
			sampleCode2 = rule + new DateTime().toString("yyyyMMdd");
		} else {
			sampleCode2 = sample2.getSafeString(QcSampledataRow.FIELD_Samplenumber);
		}

		// 初始化视频和图片
		Map<String, String> photoInfo = null;
		String photoUrl = sample1.getSafeString(QcSampledataRow.FIELD_Samplephoto);
		if (!StringUtils.IsNullOrSpace(photoUrl)) {
			photoInfo = new HashMap<>();
			photoInfo.put("urlPath", photoUrl);
			photoInfo.put("suffix", "jpg");
			int indexOf = photoUrl.lastIndexOf("/");
			if (indexOf > -1) {
				photoInfo.put("name", photoUrl.substring(indexOf + 1));
			}
		}
		Map<String, String> videoInfo = null;
		String videoUrl = sample1.getSafeString(QcSampledataRow.FIELD_Samplevideo);
		if (!StringUtils.IsNullOrSpace(videoUrl)) {
			videoInfo = new HashMap<>();
			videoInfo.put("urlPath", videoUrl);
			videoInfo.put("suffix", "mp4");
			int indexOf = videoUrl.lastIndexOf("/");
			if (indexOf > -1) {
				videoInfo.put("name", videoUrl.substring(indexOf + 1));
			}
		}
		RowBase resultMap = new RowBase();
		resultMap.put("parameterList", NonNullUtil.toList(parameterList));
		resultMap.put("labParameterList", NonNullUtil.toList(labParameterList));
		resultMap.put("qcTypeList", NonNullUtil.toList(qcTypeList));
		resultMap.put("personList", NonNullUtil.toList(personList));
		resultMap.put("photoInfo", NonNullUtil.toMap(photoInfo));

		resultMap.put("dateTime", dateTime);
		resultMap.put("sampleCode1", sampleCode1);
		resultMap.put("sampleCode2", sampleCode2);
		if (videoInfo != null) {
			resultMap.put("videoInfo", videoInfo);
		}

		resultMap.put("selectPersonList1", selectPersonList1);
		resultMap.put("selectPersonList2", selectPersonList2);
		resultMap.put("selectParameterList1", selectParameterList1);
		resultMap.put("selectParameterList2", selectParameterList2);
		resultMap.put("ValueMap1", valueMap1);
		resultMap.put("ValueMap2", valueMap2);
		return resultMap;
	}

	@Override
	public void saveTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		List<TableRowMap> tableMainList = new ArrayList<TableRowMap>();
		List<TableRowMap> tableValueList = new ArrayList<TableRowMap>();
		List<TableRowMap> tablePersonList = new ArrayList<TableRowMap>();
		JSONObject json = JSONObject.fromObject(data);
		tableMainList.addAll(TableRowMap.get(json.getJSONArray("samplingList"), QcSampledataTable.TABLE_NAME));
		tableValueList.addAll(TableRowMap.get(json.getJSONArray("valueList"), QcSampledetaildataTable.TABLE_NAME));
		tablePersonList.addAll(TableRowMap.get(json.getJSONArray("personList"), QcSamplenumberPersonTable.TABLE_NAME));
		for (TableRowMap rowMap : tableMainList) {
			FieldInterceptor interceptor = FieldInterceptor.createNotNullInterceptor(SAMPLE_DATA_ARRAY);
			rowMap.setFieldInterceptor(interceptor);
		}
		for (TableRowMap rowMap : tableValueList) {
			FieldInterceptor interceptor = FieldInterceptor.createNotNullInterceptor(QcSampledetaildataRow.FIELD_Monitorparam,
					QcSampledetaildataRow.FIELD_Monitorvalue, QcSampledetaildataRow.FIELD_Samplenumber);
			rowMap.setFieldInterceptor(interceptor);
		}
		for (TableRowMap rowMap : tablePersonList) {
			FieldInterceptor interceptor = FieldInterceptor.createNotNullInterceptor(QcSamplenumberPersonRow.FIELD_Samplenumber,
					QcSamplenumberPersonRow.FIELD_Samplepersoncode);
			rowMap.setFieldInterceptor(interceptor);
		}
		makeSureTwoSampleCodeNotEqual(tableMainList);
		makeSureSaveDataNotRepeat(tableMainList);
		makeSurePersonSizeMinThanSix(tablePersonList);
		makeSureContainLabProject(tableValueList);
		try {
			DataUtil.beginTransaction();

			JSONObject taskJson = json.getJSONObject("taskBean");
			String TASK_CODE = taskJson.optString("TASK_CODE");
			String TASK_DESC = taskJson.optString("TASK_DESC");
			preFinishOperationTask(TASK_CODE, TASK_DESC);

			List<TableRowMap> insertList = new ArrayList<>();
			insertList.addAll(tableMainList);
			insertList.addAll(tableValueList);
			insertList.addAll(tablePersonList);
			SqlUtils.prepareInsert(insertList);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public void updateTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		String taskCode = taskParam.getTaskCode();
		JSONObject json = JSONObject.fromObject(data);
		List<TableRowMap> tableMainList = new ArrayList<TableRowMap>();
		List<TableRowMap> tableValueList = new ArrayList<TableRowMap>();
		List<TableRowMap> tablePersonList = new ArrayList<TableRowMap>();
		tableMainList.addAll(TableRowMap.get(json.getJSONArray("samplingList"), QcSampledataTable.TABLE_NAME));
		tableValueList.addAll(TableRowMap.get(json.getJSONArray("valueList"), QcSampledetaildataTable.TABLE_NAME));
		tablePersonList.addAll(TableRowMap.get(json.getJSONArray("personList"), QcSamplenumberPersonTable.TABLE_NAME));
		for (TableRowMap rowMap : tableMainList) {
			FieldInterceptor interceptor = FieldInterceptor.createNotNullInterceptor(SAMPLE_DATA_ARRAY);
			rowMap.setFieldInterceptor(interceptor);
		}
		for (TableRowMap rowMap : tableValueList) {
			FieldInterceptor interceptor = FieldInterceptor.createNotNullInterceptor(QcSampledetaildataRow.FIELD_Monitorparam,
					QcSampledetaildataRow.FIELD_Monitorvalue, QcSampledetaildataRow.FIELD_Samplenumber);
			rowMap.setFieldInterceptor(interceptor);
		}
		for (TableRowMap rowMap : tablePersonList) {
			FieldInterceptor interceptor = FieldInterceptor.createNotNullInterceptor(QcSamplenumberPersonRow.FIELD_Samplenumber,
					QcSamplenumberPersonRow.FIELD_Samplepersoncode);
			rowMap.setFieldInterceptor(interceptor);
		}

		try {
			// 删除原有的数据
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			makeSureTwoSampleCodeNotEqual(tableMainList);
			makeSureSaveDataNotRepeat(tableMainList);
			makeSurePersonSizeMinThanSix(tablePersonList);
			makeSureContainLabProject(tableValueList);

			List<TableRowMap> insertList = new ArrayList<>();
			insertList.addAll(tableMainList);
			insertList.addAll(tableValueList);
			insertList.addAll(tablePersonList);
			SqlUtils.prepareInsert(insertList);
			JSONObject taskJson = json.getJSONObject("taskBean");
			String TASK_CODE = taskJson.optString("TASK_CODE");
			String TASK_DESC = taskJson.optString("TASK_DESC");
			preFinishOperationTask(TASK_CODE, TASK_DESC);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public RowBase getTaskInitData(QcTaskParam taskParam) throws Exception {
		String companyCode = taskParam.getCompanyCode();
		String pointCode = taskParam.getPointCode();
		List<RowBase> parameterList = mParameterService.getSampleParameterList(pointCode);
		List<RowBase> labParameterList = mParameterService.getLabBasicParameterList(pointCode);
		List<RowBase> qcTypeList = mDomainManager.getSampleQcTypeList();
		List<RowBase> personList = mDomainManager.getPersonList(companyCode, "1");

		String dateTime = new DateTime().toString();
		String rule = QcService.getSamplePrefix(companyCode);// 命名规则
		String sampleCode1 = rule + new DateTime().toString("yyyyMMdd");
		String sampleCode2 = rule + new DateTime().toString("yyyyMMdd");

		// 质控类型默认选第一个
		qcTypeList.get(0).put("checked", true);
		RowBase resultMap = new RowBase();
		resultMap.put("parameterList", NonNullUtil.toList(parameterList));
		resultMap.put("qcTypeList", NonNullUtil.toList(qcTypeList));
		resultMap.put("personList", NonNullUtil.toList(personList));
		resultMap.put("labParameterList", NonNullUtil.toList(labParameterList));

		resultMap.put("dateTime", dateTime);
		resultMap.put("sampleCode1", sampleCode1);
		resultMap.put("sampleCode2", sampleCode2);
		return resultMap;
	}

	// 根据站点编号或者公司编号获取运维任务
	private List<RowBase> getTaskList(String companyCode, String pointCode, String taskCode) throws Exception {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("sampleJobId", QcControl.SAMPLE.getJobId()));
		parms.add(new GlobalParameter("pointCode", pointCode));
		parms.add(new GlobalParameter("companyCode", companyCode));
		String taskSql = "select distinct t.TASK_CODE \"id\",\n"
				+ "       t.station_id \"stationCode\",\n"
				+ "       case\n"
				+ "         when t.Task_Status = '0' and t.parent_task_code is not null then\n"
				+ "          '待采样'\n"
				+ "       end \"name\",\n"
				+ "       t1.name || '  ' || to_char(t.START_TIME, 'yyyy-mm-dd hh24:mi:ss') \"des\",\n"
				+ "       t.Task_Status \"type\",\n"
				+ "       t.parent_task_code \"parentCode\",\n"
				+ "       to_char(t.START_TIME, 'yyyy-mm-dd hh24:mi:ss') \"startTime\",\n"
				+ "       to_char(t.END_TIME, 'yyyy-mm-dd hh24:mi:ss') \"endTime\",\n"
				+ "       t.FINISH_BY \"userId\"\n"
				+ "  from OP_TASK t\n"
				+ "  left join BC_SITE_INFO t1\n"
				+ "    on t1.code = t.station_id\n"
				+ " where 1 = 1\n"
				+ "   and t.parent_task_code is not null\n"
				+ "   and t.job_id = @sampleJobId\n"
				+ "   and t.wwtp_id = @companyCode\n";
		if (!StringUtils.IsNullOrSpace(taskCode)) {
			parms.add(new GlobalParameter("taskCode", taskCode));
			taskSql += "   and t.task_code = @taskCode\n";
		}
		taskSql +=" order by case\n"
				+ "            when t.station_id = @pointCode then\n"
				+ "             0\n"
				+ "            else\n"
				+ "             1\n"
				+ "          end asc";
		List<RowBase> rows = DataUtil.getSelectRows(taskSql, parms);
		return NonNullUtil.toList(rows);
	}

	// 完善任务数据
	private List<RowBase> completeTaskDataDes(List<RowBase> taskList) throws Exception {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select t.operation_task_code,\n"
				+ "       t.samplenumber,\n"
				+ "       max(t3.name) ||'  '|| wm_concat(to_char(t2.monitorparamname)) DES\n"
				+ "  from qc_sampledata t\n"
				+ "  left join qc_sampledetaildata t1\n"
				+ "    on t.samplenumber = t1.samplenumber\n"
				+ "   and t1.type = '1'\n"
				+ "  left join qc_monitorparam t2\n"
				+ "    on t2.monitorparamcode = t1.monitorparam\n"
				+ "   and t2.monitortypecode = t.monitortype\n"
				+ "   and t2.isfieldparam = '1'\n"
				+ "  left join BC_SITE_INFO t3\n"
				+ "    on t3.code = t.point\n"
				+ " group by t.operation_task_code, t.samplenumber";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		Map<String, RowBase> taskDataDesMap = new HashMap<>();
		for (RowBase rowBase : rows) {
			String taskCode = rowBase.getSafeString("operation_task_code");
			String sampleCode = rowBase.getSafeString("samplenumber");
			if (!taskDataDesMap.containsKey(taskCode)) {
				RowBase desRow = new RowBase();
				String des = rowBase.getSafeString("DES");
				desRow.put("des", des);
				desRow.put("name", sampleCode);
				taskDataDesMap.put(taskCode, desRow);
			} else {
				RowBase desRow = taskDataDesMap.get(taskCode);
				String previousSampleCode = (String) desRow.get("name");
				desRow.put("name", previousSampleCode + "," + sampleCode);
			}
		}

		for (RowBase rowBase : taskList) {
			String type = (String) rowBase.get("type");
			if ("1".equals(type)) {
				String taskCode = (String) rowBase.get("id");
				if (taskDataDesMap.containsKey(taskCode)) {
					RowBase dataRow = taskDataDesMap.get(taskCode);
					String name = (String) dataRow.get("name");
					String des = (String) dataRow.get("des");
					rowBase.put("name", name);
					rowBase.put("des", des);
				}
			}
		}
		return taskList;
	}

	// 删除任务内容
	private void executeDeleteTaskContent(String taskCode) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String mainDeleteSql = "delete from QC_SAMPLEDATA t\n" + " where t.operation_task_code = @taskCode";
		String valueDeleteSql = "delete from QC_SAMPLEDETAILDATA t\n"
				+ " where t.guid in\n"
				+ "       (select t.guid\n"
				+ "          from QC_SAMPLEDETAILDATA t\n"
				+ "          left join QC_SAMPLEDATA t1\n"
				+ "            on t1.samplenumber = t.samplenumber\n"
				+ "         where t1.operation_task_code = @taskCode)";
		String personDeleteSql = "delete from QC_SAMPLENUMBER_PERSON t\n"
				+ " where t.guid in\n"
				+ "       (select t.guid\n"
				+ "          from QC_SAMPLENUMBER_PERSON t\n"
				+ "          left join QC_SAMPLEDATA t1\n"
				+ "            on t1.samplenumber = t.samplenumber\n"
				+ "         where t1.operation_task_code = @taskCode)";
		DataUtil.ExecuteUpdateSql(valueDeleteSql, parms);
		DataUtil.ExecuteUpdateSql(personDeleteSql, parms);
		DataUtil.ExecuteUpdateSql(mainDeleteSql, parms);
	}

	// 获取有效的采样表信息
	private List<RowBase> getSampleList(String taskCode) throws Exception {
		ValidUtils.hasText(taskCode, "任务编号为空");
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "select * from QC_SAMPLEDATA t where t.operation_task_code = @taskCode order by t.ispxy";
		return DataUtil.getSelectRows(sql, parms);
	}

	// 获取有效的采样表信息
	private List<RowBase> getValueList(String taskCode) throws Exception {
		ValidUtils.hasText(taskCode, "任务编号为空");
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "select t.*,t1.ispxy from QC_SAMPLEDETAILDATA t\n"
				+ "left join qc_sampledata t1 on t1.samplenumber = t.samplenumber\n"
				+ "where t1.operation_task_code = @taskCode order by t1.ispxy";
		return DataUtil.getSelectRows(sql, parms);
	}

	// key 0表示普通 1表示平行
	private Map<String, Set<String>> getLabParameterMap(String taskCode) throws Exception {
		ValidUtils.hasText(taskCode);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "select distinct t.ispxy, t1.monitorparam\n"
				+ "  from qc_sampledata t\n"
				+ "  left join qc_sampledetaildata t1\n"
				+ "    on t1.samplenumber = t.samplenumber\n"
				+ " where t1.type = '1'\n"
				+ "   and t.operation_task_code = @taskCode";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		Map<String, Set<String>> resultMap = new HashMap<>();
		for (RowBase rowBase : rows) {
			String isPxy = rowBase.getSafeString("ispxy");
			String parameterCode = rowBase.getSafeString("monitorparam");
			if (!resultMap.containsKey(isPxy)) {
				resultMap.put(isPxy, new HashSet<>());
			}
			resultMap.get(isPxy).add(parameterCode);
		}
		return resultMap;
	}

	// 获取有效的采样表信息
	private List<RowBase> getPersonList(String taskCode) throws Exception {
		ValidUtils.hasText(taskCode, "任务编号为空");
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "select t.*,t1.ispxy from QC_SAMPLENUMBER_PERSON t\n"
				+ "left join qc_sampledata t1 on t1.samplenumber = t.samplenumber\n"
				+ "where t1.operation_task_code = @taskCode order by t1.ispxy";
		return DataUtil.getSelectRows(sql, parms);
	}

	private void validSampleList(List<RowBase> rows) throws Exception {
		ValidUtils.notEmpty(rows, "采样数据为空");
		String qcTypeCode = rows.get(0).getSafeString(QcSampledataRow.FIELD_Qctype);
		int sampleCount = QcHelper.getSampleCount(qcTypeCode);
		ValidUtils.isTrue(rows.size() == sampleCount, "采样次数有误");
		RowBase sample1 = null;
		RowBase sample2 = null;
		for (RowBase rowBase : rows) {
			if ("0".equals(rowBase.getSafeString(QcSampledataRow.FIELD_Ispxy))) {
				sample1 = rowBase;
			} else {
				sample2 = rowBase;
			}
		}
		ValidUtils.notNull(sample1, "第一组采样数据为空");
		if (sampleCount == 2) {
			ValidUtils.notNull(sample2, "第二组采样数据为空");
		}
	}

	// 保存时数据校验 - 采样人数量<=6
	private void makeSurePersonSizeMinThanSix(List<TableRowMap> tablePersonList) throws Exception {
		if (CollectionUtils.isEmpty(tablePersonList) || tablePersonList.size() <= 6) {
			return;
		}
		Map<String, List<TableRowMap>> personListMap = new HashMap<String, List<TableRowMap>>();
		boolean isMaxThanSix = false;
		for (TableRowMap bean : tablePersonList) {
			String sampleCode = (String) bean.get(QcSamplenumberPersonRow.FIELD_Samplenumber);
			if (!personListMap.containsKey(sampleCode)) {
				personListMap.put(sampleCode, new ArrayList<>());
			}
			List<TableRowMap> list = personListMap.get(sampleCode);
			list.add(bean);
			if (list.size() > 6) {
				isMaxThanSix = true;
				break;
			}
		}
		if (isMaxThanSix) {
			throw new Exception("采样人员超过6个");
		}
	}

	// 保存时数据校验 - 信息不重复
	private void makeSureSaveDataNotRepeat(List<TableRowMap> tableMainList) throws Exception {
		String sampleCodeStr = "";
		for (TableRowMap beanMap : tableMainList) {
			String sampleCode = beanMap.get(QcSampledataRow.FIELD_Samplenumber).toString();
			sampleCodeStr += "'" + sampleCode + "',";
		}
		sampleCodeStr = sampleCodeStr.substring(0, sampleCodeStr.length() - 1);
		String sql = "select t.SAMPLENUMBER\n" + "  from QC_SAMPLEDATA t\n" + " where 1 = 1\n" + "   and t.SAMPLENUMBER in (" + sampleCodeStr + ")";
		List<RowBase> rows = DataUtil.getSelectRows(sql, null);
		if (CollectionUtils.isEmpty(rows)) {
			return;
		}

		String repeatDetail = "重复的样品编号有:";
		for (RowBase rowBase : rows) {
			repeatDetail += "\n" + rowBase.getSafeString("SAMPLENUMBER");
		}
		throw new IllegalArgumentException(repeatDetail);
	}

	// 保存时数据校验 - 两组实验编号不能相同
	private void makeSureTwoSampleCodeNotEqual(List<TableRowMap> tableMainList) throws Exception {
		if (tableMainList == null || tableMainList.size() <= 1) {
			return;
		}
		String sampleCode1 = (String) tableMainList.get(0).get(QcSampledataRow.FIELD_Samplenumber);
		String sampleCode2 = (String) tableMainList.get(1).get(QcSampledataRow.FIELD_Samplenumber);
		if (sampleCode1 != null && sampleCode1.equals(sampleCode2)) {
			throw new Exception("两组样品编号相同");
		}
	}

	// 保存时数据校验 - 必须包含实验项目
	private void makeSureContainLabProject(List<TableRowMap> tableValueList) throws Exception {
		for (TableRowMap bean : tableValueList) {
			if ("1".equals(bean.get("TYPE"))) {
				return;
			}
		}
		throw new Exception("实验项目为空");
	}
}
